import os
import time
import zipfile
from datetime import datetime, timedelta
from Common.global_data import GlobalData
# === 配置项 ===
log_dir = './Outputs/LogcatLog'  # 日志文件夹路径
zip_dir = './Outputs/Zipped_logs'  # 存放压缩包的路径
check_interval = 600  # 每隔多少秒检查一次（单位：秒）
file_age_minutes = 12  # 文件超过多少分钟才打包
safety_window_minutes = 10  # 修改时间小于该时间，认为正在写入，跳过

# 确保目标目录存在
os.makedirs(zip_dir, exist_ok=True)


def get_ready_log_files(directory, age_minutes, safety_window_minutes):
    """获取符合压缩条件的日志文件"""
    current_time = datetime.now()
    eligible_files = []

    for filename in os.listdir(directory):
        if "gitkeep" in filename:
            continue
        file_path = os.path.join(directory, filename)

        if not os.path.isfile(file_path):
            continue  # 忽略子目录等非文件

        file_mtime = datetime.fromtimestamp(os.path.getmtime(file_path))
        age_delta = current_time - file_mtime

        if age_delta > timedelta(minutes=age_minutes) and age_delta > timedelta(minutes=safety_window_minutes):
            eligible_files.append(file_path)
        else:
            print(f'跳过（仍在写入或时间不足）：{filename}')

    return eligible_files


def compress_single_file(file_path, zip_dir):
    """压缩单个日志文件为zip文件"""
    file_name = os.path.basename(file_path)
    base_name, _ = os.path.splitext(file_name)
    zip_filename = f'{base_name}.zip'
    zip_path = os.path.join(zip_dir, zip_filename)

    # 创建zip文件
    try:
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            zipf.write(file_path, arcname=file_name)
            print(f'已压缩：{file_name} -> {zip_filename}')
    except Exception as e:
        print(f'压缩失败：{file_name}，错误：{e}')
        return False

    return True


def delete_file(file_path):
    """删除文件"""
    try:
        os.remove(file_path)
        print(f'已删除原文件：{file_path}')
    except Exception as e:
        print(f'删除失败：{file_path}，错误：{e}')


def main():
    print("===== 日志自动打包脚本启动 =====")
    while True:


        print(f"\n=== 扫描时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===")

        # 1. 获取符合条件的旧日志
        ready_files = get_ready_log_files(log_dir, file_age_minutes, safety_window_minutes)

        if not ready_files:
            print("没有需要压缩的日志文件。")
        else:
            for file_path in ready_files:
                # 2. 压缩单个文件
                success = compress_single_file(file_path, zip_dir)

                # 3. 压缩成功后删除原文件
                if success:
                    delete_file(file_path)

        # 4. 等待下一次扫描
        time.sleep(check_interval)
        # RunStatus=os.path.exists("main_logcat.txt")
        # if RunStatus:
        #     now = time.strftime("%Y-%m-%d_%H_%M_%S")
        #     print(now)
        #     print("接收到停止信号，任务终止")
        #     break
        #     return None


if __name__ == '__main__':
    main()
